# -*- coding: utf-8 -*-
"""
用户注册表单及相关验证
"""


from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.models import Group

attrs_dict = { 'class': 'required' }


class RegisterForm(forms.Form):
    username = forms.RegexField(regex=r'^\d{11}$',max_length=11,widget=forms.TextInput(attrs=attrs_dict),label='手机号',
                                error_messages={'required': '请填写手机号码', 'invalid':'请填写正确格式的手机号码'})
    password = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),label='密码')
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),label='再次输入密码')
    
    #必须同意网站协议
    tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
                             label='我已经阅读并同意相关的协议条款。',
                             error_messages={ 'required': "你必须同意协议条款才能注册。" })
    def clean_username(self):
        """
        '验证用户是否已经存在
        """
        try:
            User.objects.get(username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError('手机号已注册!')

    def clean(self):
        """
        '对比两个密码是否相同
        """
        cleaned_data = self.cleaned_data
        if 'password' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password'] != self.cleaned_data['password2']:
                self._errors['password'] = self.error_class(["两次输入的密码不相同"])
                del cleaned_data['password']
                del cleaned_data['password2']
        return cleaned_data
    
    def save(self, profile_callback=None):
        new_user = User.objects.create_user(self.cleaned_data['username'], "", password=self.cleaned_data['password'])
        new_user.is_active = True
        new_user.groups.add( Group.objects.get(name__iexact="customer"))
        new_user.save()
        return new_user
